﻿using RestSharp;
using System;
using System.IO;
using YouWei.Utility;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Linq;
using YouWei.Infrastructure.Models;
using System.Collections.Generic;
using YouWei.Infrastructure.Entity;
using HtmlAgilityPack;

namespace YouWei.Op.Common
{
    public static class SpidersWxComment
    {
        /// <summary>
        /// 原始图片存储路径
        /// </summary>
        static string CommentImageLocalPath = ConfigHelper.GetAppSettingValue("CommentImageTmpPath");

        /// <summary>
        /// 图片服务器Url
        /// </summary>
        static string CommentImageServerUrl = ConfigHelper.GetAppSettingValue("CommentImageServerUrl");

        public static CommentDto GetWxCommon(string urlStr)
        {
            Uri u = new Uri(urlStr);
            var entity = new CommentDto();
            var TextListUrl = u.PathAndQuery;
            RestClient client = new RestClient(u.Scheme + "://" + u.Host);
            var request = new RestRequest(TextListUrl, Method.GET);
            IRestResponse response = client.Execute(request);
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(response.Content);
            //IHtmlDocument source = new JumonyParser().Parse(response.Content);
            //处理img图片，下载并替换
            var imageDoms = htmlDoc.DocumentNode.SelectNodes("//img");

            //source.Find("img");
            if (imageDoms != null)
            {
                foreach (var item in imageDoms)
                {
                    //var srcDom = item.Attribute("src");
                    //if (srcDom == null)
                    //    srcDom = item.Attribute("data-src");

                    var srcDom = item.Attributes["src"];
                    if (srcDom == null)
                        srcDom = item.Attributes["data-src"];
                    if (srcDom == null)
                        continue;
                    //string src = srcDom.AttributeValue;
                    string src = srcDom.Value;
                    if (!string.IsNullOrWhiteSpace(src))
                    {
                        string filePath = CommentImageLocalPath;

                        string dir = Path.GetDirectoryName(filePath);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        //if (Path.GetExtension(src) == ".jpg")
                        //    return entity;
                        //替换掉//res.wx.qq.com/mmbizwap的//
                        src = Regex.Replace(src, "^//", "https://");
                        var img = ImageHelper.UrlToImage(src);
                        var fileName = "/" + Guid.NewGuid().ToString("N") + ".jpg";
                        var savePath = filePath + fileName;
                        using (Bitmap tempImage = new Bitmap(img))
                        {
                            tempImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        //item.SetAttribute("src", CommentImageServerUrl + fileName);
                        //item.SetAttribute("data-src", CommentImageServerUrl + fileName);
                        item.SetAttributeValue("src", CommentImageServerUrl + fileName);
                        item.SetAttributeValue("data-src", "");
                    }
                }
            }
            var h2s = htmlDoc.DocumentNode.SelectNodes("//h2");
            //source.Find("h2");
            if (h2s != null && h2s.Count() > 0)
            {
                //entity.CommentName = h2s.FirstOrDefault().InnerText();
                entity.CommentName = h2s[0].InnerText;
                entity.CommentDesc = entity.CommentName;
            }
            //替换&#160空格符号
            var js_content = htmlDoc.GetElementbyId("js_content");
            if (js_content != null)
            {
                entity.Detail = js_content.InnerHtml;
            }
            //entity.Detail = source.Find("#js_content").ToList().FirstOrDefault().InnerHtml().Replace("&#160;", "");
            return entity;
        }

    }
}